using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace LifeChess.Entity
{
    public class BaseChessBoard
    {
        Vector2Int size;
        BaseChess[] squareChesses;

        public void InitBoard(Vector2Int size)
        {
            if (squareChesses == null || (size.x * size.y > this.size.x * this.size.y))
            {
                squareChesses = new BaseChess[size.x * size.y];
            }
            this.size = size;
        }

        public BaseChess GetChess(Vector2Int position)
        {
            if (IsCoordinateValid(position))
            {
                return squareChesses[position.y * size.x + position.x];
            }
            return null;
        }

        public void PutChess(BaseChess chess, Vector2Int position)
        {
            if (IsCoordinateValid(position))
            {
                squareChesses[position.y * size.x + position.x] = chess;
                chess.Position = position;
                chess.OnChessDead += () =>
                {
                    squareChesses[position.y * size.x + position.x] = null;
                };
                // Put chess, callback the event of chess
                squareChesses[position.y * size.x + position.x].OnChessPutOn(this);
            }
        }

        public bool IsCoordinateValid(Vector2Int coordinate)
        {
            if (coordinate.x < 0 || coordinate.y < 0)
                return false;
            if (coordinate.x >= size.x || coordinate.y >= size.y)
                return false;
            return true;
        }

        public void UpdateChessState()
        {
            Vector2Int indexPosition = new Vector2Int();
            for (int y = 0; y < size.y; y++)
            {
                indexPosition.y = y;
                for (int x = 0; x < size.x; x++)
                {
                    indexPosition.x = x;
                    BaseChess chess = GetChess(indexPosition);
                    if (chess != null)
                        chess.UpdateLife();
                }
            }
        }
    }

}
